<template>
  <div class="app-container">
    <el-row :gutter="10">
      <!--树结构-->
      <el-col :span="isHide ? 1 : 6" :xs="24" class="relative">
        <div class="app-container-tree-border">
          <project-tree-select-inner class="cd-mb8" :projectId="projectId" @changeProject="changeProject" />
          <el-input class="cd-mb8" v-model="filterText" placeholder="请输入" clearable size="small"
            prefix-icon="el-icon-search" />
          <el-tree class="input-tree" :data="treeList" :props="defaultProps" :filter-node-method="filterNode" ref="tree"
            node-key="id" highlight-current @node-click="handleNodeClick">
            <div slot-scope="{ node, data }" class="custom-tree-node" :title="node.label" v-text="node.label"></div>
          </el-tree>
          <div class="tree-hide-button iconfont" :class="isHide ? 'icon-xiangyou' : 'icon-xiangzuo'"
            @click="() => { isHide = !isHide }">
          </div>
        </div>
      </el-col>
      <el-col :span="isHide ? 23 : 18" :xs="24">
        <div class="app-container-table-border">
          <!-- <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
            label-width="68px">
            <el-form-item label="标段id" prop="bdId">
              <el-input v-model="queryParams.bdId" placeholder="请输入标段id" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="供应商id" prop="gysId">
              <el-input v-model="queryParams.gysId" placeholder="请输入供应商id" clearable
                @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="是否当前期" prop="currentQhFlag">
              <el-input v-model="queryParams.currentQhFlag" placeholder="请输入是否当前期" clearable
                @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="期号" prop="qh">
              <el-input v-model="queryParams.qh" placeholder="请输入期号" clearable @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="期号名称" prop="qhName">
              <el-input v-model="queryParams.qhName" placeholder="请输入期号名称" clearable
                @keyup.enter.native="handleQuery" />
            </el-form-item>
            <el-form-item label="开始时间" prop="beginDate">
              <el-date-picker clearable v-model="queryParams.beginDate" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择开始时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="结束时间" prop="endDate">
              <el-date-picker clearable v-model="queryParams.endDate" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择结束时间">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="扣款截止日期" prop="chargebacksEndDate">
              <el-date-picker clearable v-model="queryParams.chargebacksEndDate" type="date" value-format="yyyy-MM-dd"
                placeholder="请选择扣款截止日期">
              </el-date-picker>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
              <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form> -->
          <el-row v-if="treeInfo && treeInfo.type == 'supplier'" :gutter="10"
            class="mb8 cd-pr8 top-right-btn small-line-height">
            <el-col :span="1.5">
              <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
                v-hasPermi="['ma:materialMeasureQh:add']">新增</el-button>
            </el-col>
          </el-row>
          <el-table border stripe v-loading="loading" :data="materialMeasureQhList"
            @selection-change="handleSelectionChange">
            <el-table-column type="index" label="序号" width="55" align="center" />
            <!-- <el-table-column label="计量期号id" align="center" prop="measureQhId" v-if="true" />
            <el-table-column label="标段id" align="center" prop="bdId" />
            <el-table-column label="供应商id" align="center" prop="gysId" />
            <el-table-column label="类型id" align="center" prop="type" /> -->
            <el-table-column label="期号名称" align="center" prop="qhName" />
            <el-table-column label="开始时间" align="center" prop="beginDate" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.beginDate, "{y}-{m}-{d}") }}</span>
              </template>
            </el-table-column>
            <el-table-column label="结束时间" align="center" prop="endDate" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.endDate, "{y}-{m}-{d}") }}</span>
              </template>
            </el-table-column>
            <el-table-column label="扣款截止日期" align="center" prop="chargebacksEndDate" width="180">
              <template slot-scope="scope">
                <span>{{ parseTime(scope.row.chargebacksEndDate, "{y}-{m}-{d}") }}</span>
              </template>
            </el-table-column>
            <el-table-column label="是否当前期" align="center" prop="currentQhFlag">
              <template slot-scope="scope">
                <dict-tag :options="dict.type.sys_number_yes_no" :value="scope.row.currentQhFlag" />
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                  v-hasPermi="['ma:materialMeasureQh:edit']">修改</el-button>
                <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                  v-hasPermi="['ma:materialMeasureQh:remove']">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum"
            :limit.sync="queryParams.pageSize" @pagination="getList" />
        </div>
      </el-col>
    </el-row>
    <!-- 添加或修改材料计量期号对话框 -->
    <jy-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <!-- <el-form-item label="标段id" prop="bdId">
          <el-input v-model="form.bdId" placeholder="请输入标段id" />
        </el-form-item>
        <el-form-item label="供应商id" prop="gysId">
          <el-input v-model="form.gysId" placeholder="请输入供应商id" />
        </el-form-item> -->
        <!-- <el-form-item label="期号" prop="qh">
          <el-input v-model="form.qh" placeholder="请输入期号" />
        </el-form-item> -->
        <el-form-item label="期号名称" prop="qhName">
          <el-input disabled v-model="form.qhName" placeholder="请输入期号名称" />
        </el-form-item>
        <el-form-item label="开始时间" prop="beginDate">
          <el-date-picker clearable v-model="form.beginDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择开始时间"
            style="width: 100%" :picker-options="beginPickerOptions">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束时间" prop="endDate">
          <el-date-picker clearable v-model="form.endDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择结束时间"
            style="width: 100%" :picker-options="endPickerOptions"> </el-date-picker>
        </el-form-item>
        <el-form-item label="扣款截止日期" prop="chargebacksEndDate">
          <el-date-picker clearable v-model="form.chargebacksEndDate" type="date" value-format="yyyy-MM-dd"
            placeholder="请选择扣款截止日期" style="width: 100%"> </el-date-picker>
        </el-form-item>
        <el-form-item label="是否当前期" prop="currentQhFlag">
          <el-radio-group v-model="form.currentQhFlag">
            <el-radio v-for="dict in dict.type.sys_number_yes_no" :key="dict.value" :label="dict.value">
              {{ dict.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </jy-dialog>
  </div>
</template>

<script>
import { querySupplierTreeList } from "@/api/base/bsBd";
import { mapGetters } from "vuex";
import { listMaterialMeasureQh, queryLastQh, getMaterialMeasureQh, delMaterialMeasureQh, addMaterialMeasureQh, updateMaterialMeasureQh } from "@/api/ma/materialMeasureQh";

import { getDateDiff } from "@/utils";

export default {
  name: "MaterialMeasureQh",
  dicts: ["sys_number_yes_no"],
  data () {
    return {
      isHide: false,
      treeList: [],
      treeInfo: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      filterText: undefined,
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 材料计量期号表格数据
      materialMeasureQhList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        bdId: undefined,
        gysId: undefined,
        type: undefined,
        currentQhFlag: undefined,
        qh: undefined,
        qhName: undefined,
        beginDate: undefined,
        endDate: undefined,
        chargebacksEndDate: undefined
      },
      projectId: undefined,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // qh: [
        //   { required: true, message: "期号不能为空", trigger: "blur" }
        // ],
        // qhName: [
        //   { required: true, message: "期号名称不能为空", trigger: "blur" }
        // ],
        beginDate: [{ required: true, message: "开始时间不能为空", trigger: "blur" }],
        endDate: [{ required: true, message: "结束时间不能为空", trigger: "blur" }],
        // chargebacksEndDate: [
        //   { required: true, message: "扣款截止日期不能为空", trigger: "blur" }
        // ],
        currentQhFlag: [{ required: true, message: "是否当前期不能为空", trigger: "change" }]
      },
      // 实际开始时间
      beginPickerOptions: {
        disabledDate: (time) => {
          let suatus = true;
          if (suatus && this.form.endDate) {
            suatus = getDateDiff(this.parseTime(time, "{y}-{m}-{d}"), this.form.endDate, "day") >= 0;
          }
          return !suatus;
        }
      },
      // 实际结束时间
      endPickerOptions: {
        disabledDate: (time) => {
          let suatus = true;
          if (suatus && this.form.beginDate) {
            suatus = getDateDiff(this.parseTime(time, "{y}-{m}-{d}"), this.form.beginDate, "day") <= 0;
          }
          return !suatus;
        }
      }
    };
  },
  computed: {
    ...mapGetters(["sysProjectId", "sysProjectList"])
  },
  watch: {
    sysProjectId (newVal, oldVal) {
      // 系统顶部选中项目变化
      this.changeProject(newVal);
    },
    filterText (val) {
      this.$refs.tree.filter(val);
    }
  },
  created () {
    this.changeProject();
  },
  methods: {
    changeProject (projectId = this.sysProjectId) {
      this.projectId = projectId;
      this.getBdTree();
    },
    getBdTree () {
      querySupplierTreeList({ projectId: this.projectId }).then((response) => {
        this.treeList = response.data;
        // 选中左侧树
        this.$nextTick(() => {
          if (this.treeList.length > 0) {
            // this.$refs.tree.setCurrentKey(this.treeList[0].id);
            // this.handleNodeClick(this.treeList[0]);
          } else {
            this.treeInfo = {};
            this.queryParams.bdId = null;
            this.queryParams.zdId = null;
            this.materialMeasureQhList = [];
            this.total = 0;
          }
        });
      });
    },
    // 筛选节点
    filterNode (value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleNodeClick (data) {
      this.treeInfo = data;
      if (data.type == "supplier") {
        this.queryParams.zdId = data.parentId; // 站点ID
        this.queryParams.gysId = data.id; // 供应商ID
        this.handleQuery();
      } else {
        // this.$message.warning("请选择供应商！");
      }
    },

    /** 查询材料计量期号列表 */
    getList () {
      this.loading = true;
      listMaterialMeasureQh(this.queryParams).then((response) => {
        this.materialMeasureQhList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel () {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset () {
      this.form = {
        measureQhId: undefined,
        zdId: this.treeInfo.parentId,
        gysId: this.treeInfo.id,
        type: undefined,
        currentQhFlag: "0",
        qh: undefined,
        qhName: undefined,
        beginDate: undefined,
        endDate: undefined,
        chargebacksEndDate: undefined
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery () {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery () {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange (selection) {
      this.ids = selection.map((item) => item.measureQhId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset();
      this.open = true;
      this.title = "添加材料计量期号";
      this.setQh();
    },
    // 动态获取期号
    setQh () {
      queryLastQh({ gysId: this.treeInfo.id }).then((res) => {
        this.form.qh = res.data;
        this.form.qhName = `第${this.form.qh}期`;
      });
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      this.loading = true;
      this.reset();
      const measureQhId = row.measureQhId || this.ids;
      getMaterialMeasureQh(measureQhId).then((response) => {
        this.loading = false;
        this.form = response.data;
        this.open = true;
        this.title = "修改材料计量期号";
      });
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.measureQhId != null) {
            updateMaterialMeasureQh(this.form)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            addMaterialMeasureQh(this.form)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const measureQhIds = row.measureQhId || this.ids;
      this.$modal
        .confirm('是否确认删除材料计量期号名称为"' + row.qhName + '"的数据项？')
        .then(() => {
          this.loading = true;
          return delMaterialMeasureQh(measureQhIds);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download(
        "ma/materialMeasureQh/export",
        {
          ...this.queryParams
        },
        `materialMeasureQh_${new Date().getTime()}.xlsx`
      );
    }
  }
};
</script>
